package modules::utilities;
use Data::Dumper;
use v5.10;
sub new {
  my ($class) = @_;
  my $self = {
               CONFIG_FILE_PATH => '',
             };
  bless $self,$class;
  return $self;
}

sub read_conf_file {
  my ($self,$conf,$conf_file_type) = @_;
  $self->{'CONFIG_FILE_PATH'}      = $conf;
  my ($user_prefs,$samples);
  
  open CONFIG,$conf or die $!;
  while (<CONFIG>) {
    chomp;                  # no newline
    s/#.*//;                # no comments
    s/^\s+//;               # no leading white
    s/\s+$//;               # no trailing white
    next unless length;     # anything left?
    my ($param, $value) = split(/\s*=\s*/, $_, 2);
    
    $value = '' if !defined $value;
    $user_prefs->{$param} = $value;
  } 
  close(CONFIG);
  
  # only perform this operation once
  if ($conf_file_type eq 'file_paths') {
    $self->create_sample_prefs( $user_prefs ) if ($conf_file_type eq 'file_paths') ;
    $self->check_files_exist( $user_prefs );
  }

  return $user_prefs;
}

sub create_sample_prefs {
  my ($self,$sample_prefs) = @_;
  
  my $groups         = [ split( /;/,$sample_prefs->{'SAMPLE_GROUPS'} ) ]; # array of sample groups as splitted by ';'
  map { push @$samples,[ split( /,/,$_ ) ] } @$groups; # array of samples whose elements contain an array of replicates
  
  $sample_prefs->{'NO_SAMPLES'     } = scalar @$groups;
  $sample_prefs->{'NO_REPLICATES'  } = scalar @{$samples->[0]};
  $sample_prefs->{'SAMPLES'        } = $samples;
  $sample_prefs->{'TOPHAT_OUT'     } = "$sample_prefs->{'PATH'}/results/$sample_prefs->{'JOB_NAME'}/TopHat/";
  $sample_prefs->{'CUFFLINKS_OUT'  } = "$sample_prefs->{'PATH'}/results/$sample_prefs->{'JOB_NAME'}/Cufflinks/";
  $sample_prefs->{'CUFFMERGE_OUT'  } = "$sample_prefs->{'PATH'}/results/$sample_prefs->{'JOB_NAME'}/Cuffmerge/";
  $sample_prefs->{'CUFFCOMPARE_OUT'} = "$sample_prefs->{'PATH'}/results/$sample_prefs->{'JOB_NAME'}/Cuffcompare/";
  
  return;
}

sub check_files_exist {
  my ($self,$conf) = @_;
  $fastq_dir = $conf->{'FASTQ_DIR'};

  foreach my $sample (@{$conf->{'SAMPLES'}}) {
    foreach my $replica (@$sample) {
      my $filename = $fastq_dir . '/' . $replica . '.txt';
      die "$filename --> $!" unless (-e $filename) ;
    }
  }
  return;
}
1;